import { Card, Button, Checkbox, Form, Input, message } from 'antd'
import logo from '../../assets/logo.png'
import './index.scss'
import { loginAction } from '@/store/actions/login'
import { useDispatch } from 'react-redux'
// 导入类型时 使用type 明确是类型
import type { DataType } from '../type'
import type { AppDispatch } from '@/store'
import { useLocation, useNavigate } from 'react-router-dom'
import { AxiosError } from 'axios'
type State = { redirectUrl?: string }
const Login: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>()
  const navigate = useNavigate()
  const location = useLocation()
  const onFinish = async (formData: DataType) => {
    try {
      await dispatch(loginAction(formData))
      const state = location.state as State
      navigate(state?.redirectUrl || '/')
      message.success('登录成功')
    } catch (error) {
      const err = error as AxiosError<{ message: string }>
      message.error(err.response?.data.message)
      // console.log(err.response.data.message)
    }
  }
  const valiCode = (_: unknown, value: boolean) => {
    // console.log(_)
    return value
      ? Promise.resolve()
      : Promise.reject(new Error('请同意用户协议'))
  }
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          name="basic"
          // initialValues={{ remember: true }} 设置表单初始默认值 remember 对应 Form.Item的name属性
          initialValues={{ agree: true, mobile: '13911111111', code: '246810' }}
          // 校验触发时机
          validateTrigger={['onBlur', 'onChange']}
          onFinish={onFinish}
          autoComplete="off">
          <Form.Item
            // name 是表单提交后获取的数据 属性名
            name="mobile"
            rules={[
              { required: true, message: '请输入您的手机号' },
              {
                pattern:
                  /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                message: '请输入正确手机号',
                validateTrigger: 'onBlur',
              },
            ]}>
            <Input placeholder="手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: '请输入您的验证码' },
              { len: 6, message: '请输入6位验证码', validateTrigger: 'onBlur' },
            ]}>
            <Input.Password placeholder="密码" />
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator: valiCode,
              },
            ]}>
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          <Form.Item>
            {/* htmlType="submit" =》指定作为表单提交按钮 会使form组件拥有 onFinish 方法*/}
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
